from flask import Flask
from flask import render_template
from flask import request,session,redirect
from urljc import urljc
from views.phcrontab import phcrontab
from views.weixin import weixin
import json
import xlwt
import time
import os
from model.urlModels import urlModels

app = Flask(__name__)
app.register_blueprint(phcrontab,url_prefix='/crontab')
app.register_blueprint(weixin,url_prefix='/weixin')
app.secret_key = 'pfgfg4543FDG$%Gh5ghgdey'

@app.route('/')
def hello_world():
    url = urlModels()
    urllist = url.get_list()
    return render_template('index.html',data=urllist)

@app.route('/doupate',methods=['POST'])
def doupate():
    urldata = json.loads(request.form['data'])
    url = urlModels()
    url.delete(isall=True)
    for i in urldata:
        if i:
            url.insert({'url':i,'status':3})
    data = {'code':1,'msg':'成功'}
    return json.dumps(data)

@app.route('/mainx/')
def home():
    if 'admin' in session:
        return render_template('index1.html')
    else:
        return redirect('/login')

@app.route('/main/')
def main():
    return render_template('main.html')

@app.route('/login/')
def login():
    return render_template('login.html')

@app.route('/login_do/',methods=['POST'])
def login_do():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        if username=='hupan' and password == 'a123851':
            j = json.dumps({'code':1,'msg':'登录成功'})
            session['admin'] = 1
            return j
        else:
            j = json.dumps({'code': 0, 'msg': '失败'})
            return j

@app.route('/tojson',methods=['POST'])
def tojson():
    if request.method =="POST":
        url = request.form['data']
        if url :
            c = urljc.culjc()
            strx = c.start(url)
            j = json.dumps(strx)
            return j
    else:
        return 'error'

@app.route('/toexcel',methods=['POST'])
def toexcel():
    if request.method == "POST":
        data = request.form['data']
        if data:
            jsdata = json.loads(data)
            fileurl = dotoexcel(jsdata)
            # response = make_response(send_file(fileurl))
            # response.headers["Content-Disposition"] = "attachment; filename=myfiles.xls;"
            # return response
            # print(fileurl)
            return fileurl

def dotoexcel(data):
    file = xlwt.Workbook()
    timeStamp = time.time()
    localTime = time.localtime(timeStamp)
    strdate = time.strftime("%m-%d", localTime)
    strTime = time.strftime("%m-%d@%H", localTime)
    table = file.add_sheet(strTime, cell_overwrite_ok=True)
    url = 'static/xls/{}/网站url检测表({}点).xls'.format(strdate,strTime)
    alignment = xlwt.Alignment()  # Create Alignment
    alignment.horz = xlwt.Alignment.HORZ_CENTER
    alignment.vert = xlwt.Alignment.VERT_CENTER
    style1 = xlwt.XFStyle()
    style1.alignment = alignment
    table.write(0, 0, 'url',style1)
    table.write(0, 1, 'IP',style1)
    table.write(0, 2, '状态',style1)
    table.write(0, 3, '连接时间',style1)
    table.write(0, 4, '速度',style1)
    for index, k in enumerate(data):
        table.write(index+1, 0, k['url'],style1)
        table.write(index+1, 1, k['ip'],style1)
        table.write(index+1, 2, k['status'],style1)
        table.write(index+1, 3, str(k['con'])+'ms',style1)
        table.write(index+1, 4, str(k['sd'])+'Kb/s',style1)
    table.col(0).width=6500
    table.col(1).width=5000
    table.col(2).width=2000
    table.col(3).width=3000
    table.col(4).width=3000

    basedir = os.path.dirname(url)
    basedir=basedir.strip()
    basedir=basedir.rstrip("\\")
    if not os.path.exists(basedir):
        os.makedirs(basedir)
    file.save(url)
    return url

       
if __name__ == '__main__':
    app.run(host = '0.0.0.0',port = 5000, debug = 'True')